package com.ay.weixin.fdc.boss.menu.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.autoreply.db.IbatisAutoReplyDao;
import com.ay.weixin.autoreply.db.IbatisAutoReplyNewsDao;
import com.ay.weixin.autoreply.db.IbatisClickEventDao;
import com.ay.weixin.autoreply.domain.ClickEvent;
import com.ay.weixin.autoreply.domain.Message;
import com.ay.weixin.autoreply.domain.MsgNews;
import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.autoreply.event.ReplySetting;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;

public class MenuEvtBinding extends Event {

	private IbatisAutoReplyDao auto_reply_dao;
	private IbatisClickEventDao click_event_dao;
	private IbatisAutoReplyNewsDao auto_reply_news_dao;
	private MenuEvt menu_evt;
	
	@Override
	public void init_property() throws Exception {
		auto_reply_dao=Container.get(IbatisAutoReplyDao.class);
		auto_reply_news_dao=Container.get(IbatisAutoReplyNewsDao.class);
		click_event_dao=Container.get(IbatisClickEventDao.class);
		menu_evt=Container.get(MenuEvt.class);
		

	}
	
	
	
	@Override
	public String default_handling_path() {
		return "/menu/msg/binding/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		Customer customer=(Customer)el.getSessionAttr("customer");
		if(customer==null){
			el.response_to_root(CustomerLogin.login_path());
			return;
		}
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		try {
			if(StringHelper.equals("add_text", el.queryPath(3))){
				add_text(el,customer.getWxprojectID());
			}else if(StringHelper.equals("update_text", el.queryPath(3))){
				update_text(el,customer.getWxprojectID());
			}else if(StringHelper.equals("delete_text", el.queryPath(3))){
				delete_text(el,customer.getWxprojectID());
			}else if(StringHelper.equals("add_new_news", el.queryPath(3))){
				add_new_news(el,customer.getWxprojectID());
			}else if(StringHelper.equals("update_news", el.queryPath(3))){
				update_news(el,customer.getWxprojectID());
			}else if(StringHelper.equals("delete_news", el.queryPath(3))){
				delete_news(el,customer.getWxprojectID());
			}
		} catch (SQLException e) {
			e.printStackTrace();
			msg=el.i18("menu.msg.bind.db.failure");
			return_to_menu(el,customer.getWxprojectID(),el.getStr("key"),msg);
		}
		
	}

	private void add_new_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		if(StringHelper.isNull(parent_key)){
			el.response_to_root("/menu");
			return;
		}
		
        //检查输入请求是否为multipart表单数据。
        boolean isMultipart = ServletFileUpload.isMultipartContent(el.request());
        if(!isMultipart){
        	System.out.println("7");
        	el.response_to_root("/menu");
        	return;
        }
        Map<String,String> params=new HashMap<String,String>();
        String file_name=UUID.randomUUID().toString()+".jpg";
        String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
        System.out.println(file_path);
        File savedFile=null;
        boolean file_uploaded=false;
        /**为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。**/
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
            File cache_dir=new File(el.getRealPath("/WEB-INF/lizar/file_pos_form_cache"));
            if(!cache_dir.exists())cache_dir.mkdirs();
            factory.setRepository(cache_dir);// 设置缓冲区目录
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");//解决文件乱码问题
            upload.setSizeMax(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);// 设置最大文件尺寸
            List<FileItem> items = upload.parseRequest(el.request());
            if(items==null||items.isEmpty()){
            	  msg=el.i18("menu.news.image.upload.nofile.found");
                  return_to_menu(el, wxproject_id,key,msg);
                  return;
            }
            Iterator<FileItem> itr = items.iterator();//所有的表单项
            while (itr.hasNext()){
                 FileItem item = (FileItem) itr.next();//循环获得每个表单项
                 if(item.isFormField()){
                	 params.put(item.getFieldName(), new String(item.get(),"utf-8"));
                	 continue;
                 }
                 String name = item.getName();//获得文件名 包括路径啊
                 if(name.toLowerCase().endsWith(".jpg")){
                     savedFile=new File(file_path);
                     if(!savedFile.getParentFile().exists()){
                    	 savedFile.getParentFile().mkdirs();
                     }
                     item.write(savedFile);
                     file_uploaded=true;
                     break;
                 }
            }
        } catch (Exception e) {
            msg=el.i18("menu.news.image.upload.failed");
            e.printStackTrace();
            return_to_menu(el, wxproject_id,key,msg);
            return;
        }
		
        if(!file_uploaded){
        	 msg=el.i18("menu.news.image.upload.nofile.found");
             return_to_menu(el, wxproject_id,key,msg);
             return;
        }
        String description=params.get("description");
        if(description==null)description="";
        
		String title=params.get("title");
		
		String url=params.get("url");
		
		if(description.length()>Keys.getLong("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("menu.news.description.max.length.exceed"),Keys.getLong("auto_reply.news_msg_description_length"));
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		if(title==null){
			msg=el.i18("menu.news.title.cannot.be.empty");
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("menu.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		if(url==null){
			msg=el.i18("menu.news.url.cannot.be.empty");
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("menu.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		int number = auto_reply_news_dao.size( wxproject_id,key);
		
		if(number>=Keys.getInt("auto_reply.one_msg_max_news")){
			 msg=String.format(el.i18("menu.news.max.news.number.exceed"),Keys.getInt("auto_reply.one_msg_max_news"));
             return_to_menu(el, wxproject_id,key,msg);
             System.out.println("5");
             return;
		}
		ClickEvent ce=null;
		try {
			ce=click_event_dao.getClickEvent(wxproject_id,key);
		} catch (SQLException e) {
			e.printStackTrace();
			msg=el.i18("menu.msg.bind.db.failure");
			return_to_menu(el, wxproject_id,key,msg);
			savedFile.deleteOnExit();
			return;
		}
		if(ce==null){
			ce=new ClickEvent();
			ce.setEvent_type("type_msg");
			ce.setKey(key);
			try {
				click_event_dao.insert(ce);
			} catch (SQLException e) {
				e.printStackTrace();
				msg=el.i18("menu.msg.bind.db.failure");
				return_to_menu(el, wxproject_id,key,msg);
				savedFile.deleteOnExit();
				return;
			}
			
		}
		Message message=null;
		
		try {
			message=auto_reply_dao.getCLICKMessage(wxproject_id,"type_msg",key,"news");
		} catch (SQLException e) {
			e.printStackTrace();
			msg=el.i18("menu.msg.bind.db.failure");
			return_to_menu(el, wxproject_id,key,msg);
			savedFile.deleteOnExit();
			return;
		}
		if(message ==null){
			message=new Message();
			message.setMatch_type("type_msg");
			message.setEvent(Keys.getStr("input_message_event_type.CLICK"));
			message.setInput(key);
			message.setMsg_type("event");
			message.setResponse_type("news");
			message.setWxproject_id(wxproject_id);
			try {
				auto_reply_dao.insert(message);
			} catch (SQLException e) {
				e.printStackTrace();
				msg=el.i18("menu.msg.bind.db.failure");
				return_to_menu(el, wxproject_id,key,msg);
				savedFile.deleteOnExit();
				return;
			}
			try {
				message=auto_reply_dao.getCLICKMessage(wxproject_id,"type_msg",key,"news");
			} catch (SQLException e) {
				e.printStackTrace();
				msg=el.i18("menu.msg.bind.db.failure");
				return_to_menu(el, wxproject_id,key,msg);
				savedFile.deleteOnExit();
				return;
			}
		}
		
		MsgNews msg_news=new MsgNews();
		msg_news.setArticle_count(0);
		msg_news.setAuto_reply_id(message.getId());
		msg_news.setDescription(description);
		msg_news.setTitle(title);
		msg_news.setUrl(url);
		msg_news.setKey(key);
		msg_news.setWxproject_id(wxproject_id);
		msg_news.setPos(auto_reply_news_dao.getMaxPos( wxproject_id,key));
		msg_news.setPic_url(ReplySetting.getRelatImagePath(el,wxproject_id, file_name));
		auto_reply_news_dao.insert(msg_news);
		
		if(msg==null){
			msg=el.i18("menu.news.add.success");
		}
		
		List<MsgNews> list=auto_reply_news_dao.getNewsList( wxproject_id,message.getId());
		el.setAttr("reply_news", list);
		return_to_menu(el, wxproject_id,el.getStr("key"),msg);
		
	}
	
	private void delete_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		long news_id=el.getLong("id");
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		if(StringHelper.isNull(parent_key)){
			el.response_to_root("/menu");
			return;
		}
		MsgNews msg_news=auto_reply_news_dao.getById(news_id);
		if(msg_news==null){
			msg=el.i18("menu.news.message.not.exist");
			el.setAttr("msg", msg);
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		String pic_url=msg_news.getPic_url();
		File f=new File(el.getRealPath(pic_url));
		System.out.println(f.getPath());
		
		click_event_dao.delete(wxproject_id,key);
		auto_reply_news_dao.delete_by_id(news_id);
		if(auto_reply_news_dao.size( wxproject_id,key)==0){
				auto_reply_dao.delete_click_message(wxproject_id,"type_msg",key,"news");
		}
		f.delete();
		msg=el.i18("menu.news.message.delete.success");
		el.setAttr("msg", msg);
		List<MsgNews> list=auto_reply_news_dao.getNewsList( wxproject_id,msg_news.getAuto_reply_id());
		el.setAttr("reply_news", list);
		return_to_menu(el, wxproject_id,el.getStr("key"),msg);
	}
	
	private void update_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		long news_id=el.getLong("id");
		String description=el.getStr("description");
		String title=el.getStr("title");
		String url=el.getStr("url");
		int pos=el.getInt("pos");
		
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		if(StringHelper.isNull(parent_key)){
			el.response_to_root("/menu");
			return;
		}
		
		if(description.length()>Keys.getInt("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("menu.news.description.max.length.exceed"),Keys.getInt("auto_reply.news_msg_description_length"));
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("menu.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("menu.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
		MsgNews msg_news=auto_reply_news_dao.getById(news_id);
		if(msg_news==null){
			 msg=el.i18("menu.news.message.not.exist");
             return_to_menu(el, wxproject_id,key,msg);
			return;
		}
		
        
		ClickEvent ce=click_event_dao.getClickEvent(wxproject_id,key);
		
		if(ce==null){
			ce=new ClickEvent();
			ce.setEvent_type("type_msg");
			ce.setKey(key);
			click_event_dao.insert(ce);
		}
		MsgNews message=new MsgNews();
		message.setId(news_id);
		message.setDescription(description);
		message.setTitle(title);
		message.setPos(pos);
		message.setUrl(url);
		message.setWxproject_id(wxproject_id);
		auto_reply_news_dao.update(message);
		
		if(msg==null){
			msg=el.i18("menu.news.update.success");
		}
		List<MsgNews> list=auto_reply_news_dao.getNewsList( wxproject_id,msg_news.getAuto_reply_id());
		el.setAttr("reply_news", list);
		return_to_menu(el, wxproject_id,el.getStr("key"),msg);
	}
	
	
	private void return_to_menu(EventLoader el,long wxproject_id,String key,String msg) throws IOException, ServletException{
		el.setAttr("msg", msg);
		if(StringHelper.isNull(key)){
			menu_evt.load_menu_sub(el,wxproject_id);
		}else{
			menu_evt.load_sub_detail(el,wxproject_id);
		}
	}
	
	private void add_text(EventLoader el,long wxproject_id) throws IOException, SQLException, ServletException{
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		if(StringHelper.isNull(parent_key)){
			el.response_to_root("/menu");
			return;
		}
		String content=el.getStr("content");
		
		if(StringHelper.isNull(content)){
			msg=el.i18("menu.text.content.cannot.be.empty");
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		
		if(content.length()>Keys.getInt("auto_reply.text_msg_conetnt_length")){
			msg=String.format(el.i18("menu.text.content.max.length.excceed"),Keys.getInt("auto_reply.text_msg_conetnt_length"));
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		
		ClickEvent ce=click_event_dao.getClickEvent(wxproject_id,key);
		if(ce==null){
			ce=new ClickEvent();
			ce.setEvent_type("type_msg");
			ce.setKey(key);
			click_event_dao.insert(ce);
		}
		Message message=auto_reply_dao.getCLICKMessage(wxproject_id,"type_msg",key);
		if(message !=null){
			msg=el.i18("menu.text.msg.only.need.one");
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		message=new Message();
		message.setMatch_type("type_msg");
		message.setContent(content);
		message.setEvent(Keys.getStr("input_message_event_type.CLICK"));
		message.setInput(key);
		message.setMsg_type("event");
		message.setResponse_type("text");
		message.setWxproject_id(wxproject_id);
		auto_reply_dao.insert(message);
		if(msg==null){
			msg=el.i18("menu.msg.add.success");
		}
		message=auto_reply_dao.getCLICKMessage(wxproject_id,"type_msg",key);
		el.setAttr("reply_msg", message);
		return_to_menu(el,wxproject_id,el.getStr("key"),msg);
	}
	
	private void update_text(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		long id=el.getLong("id");
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		if(StringHelper.isNull(parent_key)){
			el.response_to_root("/menu");
			return;
		}
		String content=el.getStr("content");
		
		if(StringHelper.isNull(content)){
			msg=el.i18("menu.text.content.cannot.be.empty");
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		
		if(content.length()>Keys.getInt("auto_reply.text_msg_conetnt_length")){
			msg=String.format(el.i18("menu.text.content.max.length.excceed"),Keys.getInt("auto_reply.text_msg_conetnt_length"));
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		
		ClickEvent ce=click_event_dao.getClickEvent(wxproject_id,key);
		
		if(ce==null){
			ce=new ClickEvent();
			ce.setEvent_type("type_msg");
			ce.setKey(key);
			click_event_dao.insert(ce);
		}
		Message message=auto_reply_dao.getById(id);
		if(message ==null){
			msg=el.i18("menu.text.msg.not.exist");
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		message.setContent(content);
		message.setResponse_type("text");
		auto_reply_dao.update_text(message);
		if(msg==null){
			msg=el.i18("menu.msg.update.success");
		}
		
		el.setAttr("reply_msg", message);
		return_to_menu(el,wxproject_id,el.getStr("key"),msg);
		
		
	}
	
	private void delete_text(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String key=el.getStr("key");
		String parent_key=el.getStr("parent_key");
		long id=el.getLong("id");
		if(StringHelper.isNull(key)){
			key=parent_key;
		}
		String msg=null;
		if(StringHelper.isNull(parent_key)){
			el.response_to_root("/menu");
			return;
		}
		
		if(auto_reply_dao.getById(id)==null){
			msg=el.i18("menu.msg.delete.not.exists");
			return_to_menu(el,wxproject_id,key,msg);
			return;
		}
		
		click_event_dao.delete(wxproject_id,key);
		auto_reply_dao.delete_by_id(id);
		if(msg==null){
			msg=el.i18("menu.msg.delete.success");
		}
		
		return_to_menu(el,wxproject_id,el.getStr("key"),msg);
	}
	
}
